<?php
namespace Admin\Controller;
use Common\Controller\BackendController;

class LogoController extends BackendController
{
    public function index()
    {
        $model = D('items_cate');
        $infos = $model->field('id,name,pid')->select();
        $datas =  $this->_getTree($infos);
        $where['logo'] = array('neq','');
        $items = $model->where($where)->field('id,name,pid,logo')->select();

        $this->assign([
            'datas'=>$datas,
            'items'=>$items
        ]);
        $this->display();
    }

    public function store()
    {
        $model = D('items_cate');
        $id = I('post.id');
        $infos = $model->where(['id'=>$id])->find();
        if (is_null($infos)) {
            $this->error('上传失败,请选择分类!');
        } else {
            if($_FILES['logo']['error'] == 0) {
                $img =  $this->getFile($_FILES);
            }
            $model->where(['id'=>$id])->save(['logo'=>$img]);
            $this->success('操作成功！', U('index'));
        }
    }

    public function edit($id)
    {
        $model = D('items_cate');
        $data = $model->find($id);
        if(IS_POST) {
            $id = I('post.id');
            $ids = I('post.ids');
            if ($id == $ids && $_FILES['logo']['error'] == 0) {
                $img =  $this->getFile($_FILES);
                $model->where(['id'=>$id])->save(['logo'=>$img]);
                $this->success('操作成功！', U('index'));
            } elseif($id != $ids && $_FILES['logo']['error'] == 0) {
                $img =  $this->getFile($_FILES);
                $model->where(['id'=>$ids])->save(['logo'=>$img]);
                $this->success('操作成功！', U('index'));
            } elseif($id != $ids && $_FILES['logo']['error'] != 0) {
                $model->where(['id'=>$ids])->save(['logo'=>$data['logo']]);
                $this->success('操作成功！', U('index'));
            } else {
                $this->success('操作成功！', U('index'));
            }
        }

        $infos = $model->field('id,name,pid')->select();
        $items =  $this->_getTree($infos);

        $this->assign([
            'data'=>$data,
            'items'=>$items
        ]);
        $this->display();
    }

    public function destroy($id)
    {
        $model = D('items_cate');
        $model->where(['id'=>$id])->save(['logo'=>'']);
    }

    public function getFile($file)
    {
        $dir = date('ym/d/');
        $result = $this->_upload($file['logo'], 'itemcate/' . $dir);
        $savename = 'data/upload/itemcate/' .$dir . $result['info'][0]['savename'];
        return $savename;
    }

    private function _getTree($data, $pid=0, $level=0)
    {
        static $_ret = array();
        foreach ($data as $k => $v){
            if($v['pid'] == $pid){
                $v['level'] = $level;
                $_ret[] = $v;
                $this->_getTree($data, $v['id'], $level+1);
            }
        }
        return $_ret;
    }
}